<template>
  <el-dialog
      title="健康信息"
      v-model="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      @close="handleClose"
  >
    <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
    >
      <el-form-item label="病史" prop="medical_history">
        <el-input
            v-model="form.medical_history"
            type="textarea"
            :rows="3"
            placeholder="请输入病史（选填）"
        />
      </el-form-item>
      <el-form-item label="用药记录" prop="medication_records">
        <el-input
            v-model="form.medication_records"
            type="textarea"
            :rows="3"
            placeholder="请输入用药记录（选填）"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {ref, reactive, computed, watch} from 'vue'
import {ElMessage, FormInstance} from 'element-plus'
import {getHealthInfo, updateHealthInfo} from '@/api/healthInfo'
import type {Elder} from '@/types/elder'

const props = defineProps<{
  modelValue: boolean
  elder: Elder | undefined
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'success'): void
}>()

const formRef = ref<FormInstance>()
const form = reactive({
  medical_history: '',
  medication_records: ''
})

const rules = {
  medical_history: [{required: false, message: '请输入病史', trigger: 'blur'}],
  medication_records: [{required: false, message: '请输入用药记录', trigger: 'blur'}]
}

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 获取健康信息
const fetchHealthInfo = async () => {
  if (!props.elder) return
  try {
    const healthInfo = await getHealthInfo(props.elder.id)
    form.medical_history = healthInfo?.medical_history || ''
    form.medication_records = healthInfo?.medication_records || ''
  } catch (error) {
    console.error('获取健康信息失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value || !props.elder) return

  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    const submitData = {
      elderId: props.elder.id,
      medical_history: form.medical_history || null,
      medication_records: form.medication_records || null
    }

    await updateHealthInfo(submitData)
    ElMessage.success('更新成功')
    emit('success')
    dialogVisible.value = false
  } catch (error) {
    console.error('更新失败:', error)
  }
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
  form.medical_history = ''
  form.medication_records = ''
  formRef.value?.clearValidate()
}

// 监听对话框显示状态
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    fetchHealthInfo()
  }
})
</script>